<?php
namespace app\api\controller;
header('content-type:application:json;charset=utf8');  
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Credentials:true');  
header('Access-Control-Allow-Methods:*');  
header('Access-Control-Allow-Headers:x-requested-with,content-type'); 
use app\common\controller\Api;
use think\Db;
use think\Session;
use think\Config;
use wechat\JSSDK;
use think\Request;
use think\Cache;
use function GuzzleHttp\json_decode;
use function GuzzleHttp\json_encode;

/**
 * @title 查询数据接口
 */
class Output extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function __construct($ids)
    {
        $id = Cache::get('userid'.$ids);
        $userid = Db::name('user')->field('id')->where(['id'=>$id])->find();
        if(!$id && !$userid){
            $arr['code'] = 0;
            $arr['msg'] = '请先登录';
            echo json_encode($arr);
            die;
        }
    }
  

    // /**
    //  * @title 获取总分数
    //  * @url /api/Output/GetTotalScore
    //  * @method post
    //  * @param name:ids type:int require:1 desc:用户ID
    //  * @return image:头像
    //  * @return total_score:总分数
    //  */
    // public function GetTotalScore($ids){
    //     $id = Cache::get('userid'.$ids);
    //     if($id){
    //         $result = Db::name('points')->field('total_score')->where(['user_id'=>$id])->find();
    //         if($result){
    //             $result['image'] = $this->GetImage($id);
    //             $this->success('请求成功',$result,'200','json');
    //         }else{
    //             $result['total_score'] = 0;
    //             $result['image'] = $this->GetImage($id);
    //             $this->success('请求成功',$result,'200','json');
    //         }
    //     }else{
    //         $this->error('请登录！！',false,'300','json');
    //     }
    // }


    /**
     * @title 获取头像
     * @url /api/Output/GetUserImage
     * @method post
     * @param name:ids type:int require:1 desc:用户ID
     * @return data:用户头像
     */
    public function GetUserImage($ids){
        if(Request::instance()->post()){
            $id = Cache::get('userid'.$ids);
            $image = Db::name('user')->field('image')->where(['id'=>$id])->find();
            $this->success('请求成功',$image['image'],'200','json');
        }
    }

 /**
     * @title 活动是否结束
     * @url /api/Output/GetTime
     * @method post
     * @param name:ids type:int require:1 desc:用户ID
     * @return Time:活动是否结束（true=未结束，false=已结束/未开始）
     */
    public function GetTime($ids){
        if(Request::instance()->post()){
            $time = strtotime(date('Y-m-d H:i:s'));
            $startdate = strtotime(Config::get('date.startdate'));
            $enddate = strtotime(Config::get('date.enddate'));
            if($time < $startdate){
                $this->error('活动未开始',false,'200','json');
            }elseif($time > $startdate && $time < $enddate){
               $this->success('活动进行中',true,'200','json');
            }else{
                $this->error('活动已结束',false,'200','json');
            }
            
        }
    }


    /**
     * @title 获取随机数（取第6个数字）
     * @url /api/Output/GetGetRand
     * @method post
     * @param name:ids type:int require:1 desc:用户ID
     * @return data:10个随机数
     */
    public function GetRand($ids){
        $id = Cache::get('userid'.$ids);
        if($id){
            $arr = [];
            for($i=0;$i<=9;$i++){
                $arr[] = rand(1,100);        
            }
            //var_dump($arr);
            Cache::set('userrand'.$id,$arr[5]);
            $this->result('请求成功',$arr,'200','json');
        }
    }


    /**
     * @title 微信分享配置信息
     * @url /api/Output/index
     * @method post
     * @param name:ids type:int require:1 desc:用户ID
     * @param name:url type:string require:1 desc:当前页面链接地址
     * @return appId:微信appid
     * @return nonceStr:随机生成的字符串
     * @return timestamp:生成签名的时间戳 
     * @return url:链接地址
     * @return signature:生成的签名
     */
    public function index($url)
    {   
        //var_dump($url);exit;
        $appid = Config::get('wechat.appid');
        $appsecret = Config::get('wechat.appsecret');
        $jssdk = new JSSDK($appid,$appsecret);
        $signPackage = $jssdk->GetSignPackage($url); 
       $this->success('请求成功',$signPackage,'200','json');
    }


    /**
     * @title 分数排行榜
     * @url /api/Output/Ranking
     * @method post
     * @param name:ids type:int require:1 desc:用户ID
     * @return Image:头像
     * @return UserName:用户名
     * @return TotalScore:总分
     */
    public function Ranking(){
        $result = Db::name('points')->field('user_id,total_score')->order('total_score desc')->select();
        if($result){
            $arr = [];
            foreach($result as $key => $val){
                $arr[$key]['Image'] = $this->GetImage($val['user_id']);
                $arr[$key]['UserName'] = $this->GetUserName($val['user_id']);
                $arr[$key]['TotalScore'] = $val['total_score'];
            }
            $this->success('请求成功',$arr,'200','json');
        }else{
            $this->error('未查询到此数据',array(),'300','json');
        }
       
    }



    /**
     * @title 获取助力好友接口
     * @url /api/Output/GetFriend
     * @method post
     * @param name:ids type:int require:1 desc:用户ID
     * @return Image:头像
     * @return UserName:用户名
     * @return Code:用户编号
     * @return TotalScore:总分
     * @return Sort:排名(false=未上榜)
     * @return List:助力好友名单@
     * @List Image:头像 UserName:用户名
     */
    public function GetFriend($ids){
        $params = Cache::get('userid'.$ids);
        if($params){
            $arr = [];
            $arr['Image'] = $this->GetImage($params);
            $arr['UserName'] = $this->GetUserName($params);
            $arr['Code'] = $this->GetUserCode($params);
            $arr['List'] = $this->GetUser($params);
            $userinfo = Db::name('points')->field('user_id,total_score')->where(['user_id'=>$params])->find();
            if($userinfo){
                $where['total_score'] = ['>',$userinfo['total_score']];
                $count = Db::name('points')->where($where)->count();
                $arr['TotalScore'] = $userinfo['total_score'];
                $arr['Sort'] = $count+1;
            }else{
                $arr['TotalScore'] = 0;
                $arr['Sort'] = false;
            }
            $this->success('请求成功',$arr,'200','json');
        }else{
            $this->error('请登录！！',false,'200','json');
        }
    }


    /**
     * @title 好友助力页面接口
     * @url /api/Output/GetFriends
     * @method post
     * @param name:ids type:int require:1 desc:用户ID
     * @param name:friendid type:int require:1 desc:被助力好友ID
     * @return Image:好友头像
     * @return TotalScore:好友成绩
     */
    public function GetFriends($ids,$friendid){
        if(Request::instance()->post()){
            $id = Cache::get('userid'.$ids);
            $points = Db::name('points')->field('user_id,total_score')->where(['user_id'=>$friendid])->find();
            $arr = [];
            if($points){
                $arr['Image'] = $this->GetImage($points['user_id']);
                $arr['TotalScore'] = $points['total_score'];
            }else{
                $arr['Image'] = $this->GetImage($friendid);
                $arr['TotalScore'] = 0;
            }
            
            $this->success('请求成功',$arr,'200','json');
        }
    }


    /**
     * @title 获取该用户是否已为次好友助力过
     * @url /api/Output/GetIsFriend
     * @method post
     * @param name:ids type:int require:1 desc:用户ID
     * @param name:friendid type:int require:1 desc:被助力好友ID
     * @return data:是否助力过（false=已助力过；true=未助力过）
     */
    public function GetIsFriend($ids,$friendid){
        if(Request::instance()->post()){
            $id = Cache::get('userid'.$ids);
            if($id){
                //$params = $this->request->post('friendid');
                $starttime = strtotime(date('Y-m-d 0:0:0'));
                $endtime = strtotime(date('Y-m-d 23:59:59'));
                $wherecount['createtime'] = ['between',[$starttime,$endtime]];
                $wherecount['friend_id'] = $friendid;
                $count = Db::name('resurgence')->where($wherecount)->count();
                if($count>=3){
                    $this->error('今日复活次数已满',false,'200','json');
                }else{
                    if(is_numeric($friendid)){
                        $where['user_id'] = Cache::get('userid'.$ids);
                        $where['friend_id'] = $friendid;
                        $result = Db::name('resurgence')->where($where)->find();
                        if($result){
                            $this->success('已经助力过啦',false,'200','json');
                        }else{
                            $this->success('未助力过',true,'200','json');
                        }
                    }else{
                        $this->error('请输入正确的好友ID',false,'303','json');
                    }
                }
            }else{
                $this->error('请登录！！',false,'300','json');
            }
        }
    }


    /**
     * @title 获取目前可玩次数
     * @url /api/Output/GetNumber
     * @method post
     * @param name:ids type:int require:1 desc:用户ID
     * @return NumberCount:剩余可玩次数
     * @return ShareCount:剩余分享次数
     */
    public function GetNumber($ids){
        $id = Cache::get('userid'.$ids);
        if($id){
            $Totalwhere['friend_id'] = $id;
            $starttime = strtotime(date('Y-m-d 0:0:0'));
            $endtime = strtotime(date('Y-m-d 23:59:59'));
            $Totalwhere['createtime'] = ['between',[$starttime,$endtime]];
            $totalcount = Db::name('resurgence')->where($Totalwhere)->count();
            $userwhere['user_id'] = $id;
            $userwhere['createtime'] = ['between',[$starttime,$endtime]];
            $nowcount = Db::name('particular')->where($userwhere)->count();
            $arr = [];
            if($nowcount<4){
                $count = ($totalcount+1)-$nowcount;
                if($count>4){
                    $count = 4;
                }
            }else{
                $count = 0;
            }
            $arr['NumberCount'] = $count;
            if($totalcount > 3){
                $shareCount = 0;
            }else{
                $shareCount = 3-$totalcount;
            }
            $arr['ShareCount'] = $shareCount;
            
            $this->success('请求成功',$arr,'200','json');
        }else{
            $this->error('请登录！！',false,'300','json');
        }
    }


    private function GetUser($userid){
        $friend = Db::name('resurgence')->field('user_id,FROM_UNIXTIME(createtime,"%Y-%m-%d") as CreateDate')->where(['friend_id'=>$userid])->order('createtime desc')->select();
        $arr = [];
        foreach($friend as $k => $v){
            $arr[$k]['Image'] = $this->GetImage($v['user_id']);
            $arr[$k]['UserName'] = $this->GetUserName($v['user_id']);
            $arr[$k]['CreateDate'] = $v['CreateDate'];
        }
        return $arr;
    }


    /**
     * @title 今日剩余分享次数
     * @url /api/Output/GetShare
     * @method post
     * @param name:ids type:int require:1 desc:用户ID
     * @return data:剩余分享次数
     */
    public function GetShare($ids){
        $id = Cache::get('userid'.$ids);
        if($id){
            $time = strtotime(date('Y-m-d'));
            $result = Db::name('share')->field('share')->where(['user_id'=>$id,'createtime'=>$time])->find();
            if($result){
                $count = 3-$result['share'];
                if($count>0){
                    $this->success('请求成功',$count,'200','json');
                }else{
                    $count = 0;
                    $this->error('请求成功',$count,'200','json');
                }
            }else{
                $count = 3;
                $this->success('请求成功',$count,'200','json');
            }
        }else{
            $this->error('请登录！！',false,'300','json');
        }
      
    }

    /**
     * @title 获取分享用户名称
     * @url /api/Output/GetUserNameShare
     * @method post
     * @param name:ids type:int require:1 desc:用户ID
     * @return data:用户名
     */
    public function GetUserNameShare($ids){
        if(Request::instance()->post()){
            $id = Cache::get('userid'.$ids);
            $username = Db::name('user')->field('username')->where(['id'=>$id])->find();
            if($username){
                $this->success('请求成功',$username['username'],'200','json');
            }else{
                $this->error('未查询到此信息',false,'200','json');
            }
        }
    }

    private function GetImage($userid){
        $image = Db::name('user')->field('image')->where(['id'=>$userid])->find();
        return $image['image'];
    }
    private function GetUserName($userid){
        $image = Db::name('user')->field('username')->where(['id'=>$userid])->find();
        return $image['username'];
    }
    private function GetUserCode($userid){
        $image = Db::name('user')->field('code')->where(['id'=>$userid])->find();
        return $image['code'];
    }



}




?>